﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace CommonLib.Lexer;

[Order(1)]
public class UpdateLexer : BaseLexer
{
    public override bool Check()
        => Txt.StartsWith("UPDATE ");

    protected override BaseCodeEntity Run()
    {
        var txt = Real.TrimEnd(';');
        var entity = new UpdateCodeEntity
        {
            EndComment = Comment,
            Head = Regex.Match(txt, "(.*?)SET\\s+").Value
        };
        var sets = Regex.Match(txt, "SET\\s+(.*)").Result("$1");
        if (sets.Contains(" WHERE"))
        {
            var where = sets[sets.LastIndexOf(" WHERE")..].Trim();
            if (where.IsFull())
            {
                sets = sets.Replace(where, "");
                entity.Where = SqlFactory.Create(where).Execute();
            }
        }
        var arr = sets.TrimSplit(',');
        for (int i = 0; i < arr.Length; i++)
        {
            var item = arr[i];
            while (!item.IsFull())
            {
                var next = arr[++i];
                item = $"{item} {next}";
            }
            var left = item[..item.IndexOf('=')].Trim();
            entity.Cols.Add(left);
            var right = item[(item.IndexOf('=') + 1)..].Trim();
            entity.Vaules.Add(SqlFactory.Create(right).Execute());
        }
        return entity;
    }
}
